package io.github.uicdb.badskill.clent.impl;

import io.github.uicdb.badskill.BadSkill;
import io.github.uicdb.badskill.network.NetWorking;
import io.github.uicdb.badskill.network.QueryAttributePackage;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.ai.attributes.Attribute;
import org.jetbrains.annotations.NotNull;

import java.util.*;

public class AttributeScreen extends Screen {
    public static final Map<Attribute,Double> SYNC_MAP=new HashMap<>();
    public static final ResourceLocation BACKGROUND=new ResourceLocation(BadSkill.MODID,"textures/gui/attribute_background.png");
    public static void sync(){
        NetWorking.simpleChannel.sendToServer(new QueryAttributePackage());
    }
    public AttributeScreen() {
        super(Component.literal("attributes"));
        sync();
    }
    int x,y,imageWidth,imageHeight;
    protected VecScTextView textView;
    @Override
    protected void init() {
        super.init();
        var width= Minecraft.getInstance().getWindow().getGuiScaledWidth();
        var height= Minecraft.getInstance().getWindow().getGuiScaledHeight();
        imageWidth= (int) (146*getScale());
        imageHeight= (int) (180*getScale());
        x= (width - imageWidth) / 2;
        y= (height-imageHeight)/2;
        assert minecraft!=null;
        addRenderableWidget(textView=new VecScTextView(px(17),py(20),(int)((130-17)*getScale()),(int)(getScale()*(155-20)), this::getTexts));
        textView.setTextScale(1f);
    }
    private  List<? extends Component> getTexts(){
        List<MutableComponent> components=  new ArrayList<>();
        SYNC_MAP.entrySet().stream().sorted(Comparator.comparing(o -> o.getKey().getDescriptionId())).forEach((entry) -> {
            var name = Component.translatable(entry.getKey().getDescriptionId());
            MutableComponent c = Component.translatable("text.attribute.name", name, String.format("%.1f", entry.getValue()));
            components.add(c);
        });
        return components;
    }

    @Override
    public void render(@NotNull GuiGraphics guiGraphics, int p_281550_, int p_282878_, float p_282465_) {
        renderBackground(guiGraphics);
        super.render(guiGraphics, p_281550_, p_282878_, p_282465_);
    }

    @Override
    public void renderBackground(@NotNull GuiGraphics guiGraphics) {
        super.renderBackground(guiGraphics);
        guiGraphics.blit(BACKGROUND,px(0),py(0),0,0,imageWidth,imageHeight,imageWidth,imageHeight);
    }

    private int px(int dx){
        return (int) (x+dx*getScale());
    }
    private int py(int dy){
        return (int) (y+dy*getScale());
    }
    private double getScale(){
        return 1.2;
    }
}
